package com.qfedu.dao.impl;

import com.qfedu.dao.IUserDao;
import com.qfedu.entity.User;
import com.qfedu.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements IUserDao {
    @Override
    public User checkUser(String username, String password) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("select username,password,flag,id from user where username = ? and password = ?",new BeanHandler<User>(User.class),username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public int addUser(String username, String password, String email, String gender ,int flag, String code) {
        int update = 0;
        try {
            QueryRunner queryRunner = new QueryRunner();
            update = queryRunner.update(JDBCUtil.getConnection(), "insert into user(username,password,email,gender,flag,code,role) values (?,?,?,?,?,?,?)", username, password, email, gender, flag, code, 0);
            return update;
            //return new QueryRunner(JDBCUtil.getDataSource()).update("insert into user(username,password,email,gender,flag,code,role) values (?,?,?,?,?,?,?)",username,password,email,gender,flag,code,0);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public User checkUserByName(String username) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("select username from user where username = ?",new BeanHandler<User>(User.class),username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public User checkUserByEmail(String email) {
        try {
            return new QueryRunner(JDBCUtil.getDataSource()).query("select email from user where email = ?",new BeanHandler<User>(User.class),email);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateFlagByCode(String code,String email) {
        QueryRunner queryRunner = new QueryRunner();
        int update = 0;
        try {
            update = queryRunner.update(JDBCUtil.getConnection(),"update user set flag = ? where email = ? and code = ?", 1, email, code);
            return update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

//    public static void main(String[] args) {
//        UserDaoImpl userDao = new UserDaoImpl();
//        User admin = userDao.checkUser("admin", "123");
//        System.out.println(admin);
//    }

}
